package dragon.modules.system.user.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import dragon.core.db.DML;
import dragon.core.exception.ExceptionHandler;
import dragon.core.system.po.SysUser;
import dragon.core.system.po.SysUserGroupLink;

public class UserGroupLinkDaoImpl {

	public boolean saveUserGroupLink(SysUserGroupLink usergroup) throws ExceptionHandler {
		return DML.saveOrUpdateObject(usergroup) > 0 ? true : false;
	}

	public boolean deleteUserGroupLink(SysUserGroupLink usergroup) throws ExceptionHandler {
		if (usergroup.getUsergroupid() == 0) {
			return false;
		}
		if (usergroup.getUserid() == 0) {
			return false;
		}
		return DML.executeUpdate("delete from " + SysUserGroupLink.tableName + " where userid=" + usergroup.getUserid() + " and usergroupid=" + usergroup.getUsergroupid()) > 0 ? true : false;
	}

	public List<SysUser> loadGroupUsers(int Groupid) throws ExceptionHandler {
		String sql = "Select * from " + SysUserGroupLink.tableName + " ugl left join " + SysUser.tableName + " u on ugl.UserID=u.id where ugl.UserGroupID=" + Groupid;
		List<SysUser> result = new ArrayList<SysUser>();
		List<Map<String, Object>> list = DML.query(sql);
		for (Map<String, Object> m : list) {
			SysUser user = new SysUser();
			user.setId(Integer.parseInt(m.get("ID").toString()));
			user.setLoginname(m.get("LOGINNAME").toString());
			user.setUsername(m.get("USERNAME").toString());
			result.add(user);
			user = null;
		}
		sql = null;
		list = null;
		return result;
	}

	public void deleteUserGroupLink(int userid) throws ExceptionHandler {
		DML.executeUpdate("delete from " + SysUserGroupLink.tableName + " where UserID=" + userid);
	}

	public int[] getGroupIdByUserID(int id) throws ExceptionHandler {
		List<Map<String, Object>> list = DML.query("select * from " + SysUserGroupLink.tableName + " where userid=" + id);
		if (list.size() > 0) {
			int[] ids = new int[list.size()];
			for (int i = 0; i < list.size(); i++) {
				ids[i] = Integer.parseInt(list.get(i).get("USERGROUPID").toString());
			}
			return ids;
		} else {
			return null;
		}
	}

}
